# from datetime import date
from flask import Flask,request
import json
from cworld import Enveronment
import random
from robot import Robot

app=Flask(__name__)
env=Enveronment()
is_byhuman=True
robot_obs=[]
human_obs=[]
robot=Robot()
robot2=Robot()

@app.route('/')
def index():
    with open('index.html','r',encoding='utf-8')as f:
        html=f.read()
    return html
@app.route('/see')
def see():
    html='''

<body>
<canvas id="box" width="50" height="50" style="border:1px solid #000000;
background: #ffffff">您的浏览器不支持 HTML5 canvas 标签。</canvas>
</body>
<script src="/js/jquery.min.js"></script>
<script src="/js/init.js"></script>
<script src="/js/topy.js"></script>
<script src="/js/tools.js"></script>
<script>
window.refreshEvent = setInterval(refresh, 50, false);
function refresh() {
    draw(topy("see",0))
}
</script>
    '''
    return html
@app.route('/js/<name>')
def js_file(name=''):
    try:
        with open('js/'+name,'r',encoding='utf-8')as f:
            content=f.read()
        return content
    except:
        return 'Not Found!'

@app.route('/topy',methods=['POST'])
def topy():

    global robot_obs
    global human_obs
    global robot
    global robot2
    global env
    global is_byhuman

    data=request.get_data()
    function_name,parameters=json.loads(data)
    # print(function_name,parameters)
    if function_name=='print':
        print(parameters)
    elif function_name=='reset':

        obs_list=env.reset(parameters[0],2)
        
        human_obs=obs_list[0]
        robot_obs=obs_list[1]

        obs=json.dumps(human_obs)
        return obs
    elif function_name=='step':
        if is_byhuman:
            obs_list,reward_list,done=env.step([int(parameters[0]),robot.decide(robot_obs)])
        else:
            obs_list,reward_list,done=env.step([robot2.decide(human_obs),robot.decide(robot_obs)])

        # sb_list=env.step([int(parameters[0]),random.randint(0,env.ACT_DIM-1)])

        human_obs=obs_list[0]
        robot_obs=obs_list[1]

        step_result=[human_obs,reward_list[0],done]
        step_result=json.dumps(step_result)
        return step_result
    elif function_name=="see":
        return json.dumps(human_obs)

    return "0"

if __name__ == "__main__":
    # http://0.0.0.0:5000
    app.run(host='0.0.0.0', port=5000, debug = True)